package com.ygxsk.carhome.retrofit;

import android.text.TextUtils;
import android.webkit.WebSettings;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.tencent.mmkv.MMKV;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;

public class NetworkManager {


    /**
     * 该界面之中单独使用的 isReleaseInManager 标识 为了区分切换后门用的 是【正式环境】还是【测试环境】
     */
    private boolean isReleaseInManager = ApiService.IS_RELEASE;

    //正式环境2018年05月04日
    //public static final String OFFICIAL = "https://wuyeapi.91dgj.com/";

    /**
     * 正常的当前在用的基础Url，这是内存之中存动态的存入的一份
     */
    private String public_url_prefix = getReleaseInManger() ? ApiService.OFFICIAL_BASEURL : ApiService.TEST_BASEURL;


    public boolean getReleaseInManger() {
        //LogUtils.d("itchen-getReleaseInManger---isReleaseInManager--->" + isReleaseInManager);
        return isReleaseInManager;
    }

    /**
     * 只有在切换环境之中用到过一次
     */
    public void setReleaseInManager(boolean _isReleaseInManager) {
        this.isReleaseInManager = _isReleaseInManager;
        //LogUtils.d("itchen-setReleaseInManager--设置-isReleaseInManager--->" + isReleaseInManager);

        //如果发现是切换用户环境，那么需要将retrofit的值清空
        if (MMKV.defaultMMKV().decodeBool(ConstantSign.ISOPERATEDOOR)) {

            //重新赋值，这个时候还必须是 二选一的ApiService之中的值内容；
            public_url_prefix = getReleaseInManger() ? ApiService.OFFICIAL_BASEURL : ApiService.TEST_BASEURL;
            //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "即将设置 retrofit = null ，并且当前的 public_url_prefix=>" + public_url_prefix);

            retrofit = null;
            initRetrofitRxJava();

        }
    }

    /**
     * 获取系统配置
     */
    public String getSystemConfig() {

        //每次重新进入app isRelease始终是默认值
        //String systemConfigHost = isRelease() ? OFFICIAL : TEST;
        //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "-getSystemConfig-获取的值=>" + (getReleaseInManger() ? ApiService.OFFICIAL_BASEURL : ApiService.TEST_BASEURL) + "/pub/v1/config/getConfig");

        //2021-6-14 16:43:27 首次安装的时候会导致（预加载图片）可能 前缀是空的，所以这里暂时设定为和systemconfig是保持一致的。
        MMKV.defaultMMKV().encode(ConstantSign.PUBLIC_URL_PREFIX, getReleaseInManger() ? ApiService.OFFICIAL_BASEURL : ApiService.TEST_BASEURL);

        //Log.d("itchen", systemConfigHost);
        //LogUtils.d("itchen-cur-environment----->"+SPUtils.getInstance().getString(ConstantApi.ENVIRONMENT));

        return getReleaseInManger() ? ApiService.OFFICIAL_BASEURL : ApiService.TEST_BASEURL + "/pub/v1/config/getConfig";
    }

    /**
     * 这种适用于直接使用地址访问h5的,暂时用不到
     * 然后这个也出现在token的使用之上
     */
    public String getPublic_url_prefix() {
        //至少这一次的赋值还必须是  ApiService 之中，而不是从systemConfig之中获取的；
        return public_url_prefix;
    }


    public void setPublic_url_prefix_form_getSystemConfig(String _public_url_prefix_form_getsystemconfig) {

        if (!TextUtils.isEmpty(_public_url_prefix_form_getsystemconfig)) {

            //做个比较，因为有可能后台返回的值和我得ApiService.OFFICIAL_BASEURL的设置是不同的，
            //例如初始设置https://api.ygxpt.com/，但是后台给https://wuyeapi.91dgj.com/.
            if (TextUtils.equals(public_url_prefix, _public_url_prefix_form_getsystemconfig)) {
                this.public_url_prefix = _public_url_prefix_form_getsystemconfig;
            } else {
                //如果不相同，那么需要重新设置retrofit,因为现在public_url_prefix是切换后门赋予的
                this.public_url_prefix = _public_url_prefix_form_getsystemconfig;
                retrofit = null;
                initRetrofitRxJava();
            }

            //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "setPublic_url_prefix之后 的 public_url_prefix =>" + getPublic_url_prefix());

        } else {
            //这种还相当于还原到原始赋值,因为发现OKhttp3.14的bug
            this.public_url_prefix = getReleaseInManger() ? ApiService.OFFICIAL_BASEURL : ApiService.TEST_BASEURL;
            //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "是空的情况---setPublic_url_prefix之后 的 public_url_prefix =>" + getPublic_url_prefix());
        }

    }
    //---------------------------------------------------------------------------------------------------------------------------------------------

    private static volatile NetworkManager instances;
    private static volatile OkHttpClient okHttpClient;
    private static volatile Retrofit retrofit;

    // 请求超时时间
    //private static final int DEFAULT_TIMEOUT_MILLISECOND = 60 * 1000;

    public static NetworkManager getInstance() {

        if (instances == null) {
            synchronized (NetworkManager.class) {
                if (instances == null) {
                    instances = new NetworkManager();
                }
            }
        }
        return instances;
    }


    private OkHttpClient initClient() {

        if (okHttpClient == null) {

            synchronized (NetworkManager.class) {

                if (okHttpClient == null) {
                    //请求日志打印
                    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> {
                        try {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, URLDecoder.decode(message, "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            if (e != null) {
                                //LogUtils.d(ConstantApi.LOGCAT_NOMAL, e.getLocalizedMessage());
                            } else {
                                //LogUtils.d(ConstantApi.LOGCAT_NOMAL, "e的值是空~");
                            }
                            e.printStackTrace();
                            //MLog.e(message);
                        }
                    });

                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

                    //注释1：设置OkHttpClient
                    okHttpClient = new OkHttpClient.Builder()
                            .sslSocketFactory(new NetworkSSL(TrustManager.trustAllCert), TrustManager.trustAllCert)
                            .addInterceptor(new Interceptor() {
                                @NonNull
                                @Override
                                public Response intercept(@NonNull Chain chain) throws IOException {

                                    //添加统一通用header， 不会覆盖前面的header---addheader
                                    //.addHeader("header-key", "value1")
                                    //.addHeader("header-key", "value2");

                                    //添加统一通用header， 会覆盖前面的header
                                    //.header("headerkey", "header-value");

                                    //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "token=>" + MMKV.defaultMMKV().decodeString(ConstantApi.P_TOKEN));
                                    //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "uuid=>" + MMKV.defaultMMKV().decodeString(ConstantApi.P_UUID_UNIQUEDEVICEID_ANDROIDID));

                                    Request request = request = chain.request()
                                            .newBuilder()
                                            .header("Content-Type", "application/json; charset=UTF-8")//@Headers({"Content-Type: application/json", "Accept: application/json"})//需要添加头
                                            .header("User-Agent", Parameterkey.USER_AGENT_PREFIX + WebSettings.getDefaultUserAgent(Utils.getApp()))//添加真正的头部
                                            .build();

                                    if (!TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_UUID_UNIQUEDEVICEID_ANDROIDID, DeviceUtils.getUniqueDeviceId()))
                                            && !TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN))) {

                                        request = chain.request()
                                                .newBuilder()
                                                .header("Content-Type", "application/json; charset=UTF-8")//@Headers({"Content-Type: application/json", "Accept: application/json"})//需要添加头
                                                .header("User-Agent", Parameterkey.USER_AGENT_PREFIX + WebSettings.getDefaultUserAgent(Utils.getApp()))//添加真正的头部
                                                .header("Devicecode", MMKV.defaultMMKV().decodeString(ConstantSign.P_UUID_UNIQUEDEVICEID_ANDROIDID, DeviceUtils.getUniqueDeviceId()))//Devicecode: 268c7c773de7b3cc1af50370275699324
                                                .header("Usertoken", MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN))//Usertoken: f731344a03d4a273fc8437628490634e
                                                .build();

                                    } else if (!TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_UUID_UNIQUEDEVICEID_ANDROIDID, DeviceUtils.getUniqueDeviceId()))
                                            && TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN))) {

                                        request = chain.request()
                                                .newBuilder()
                                                //.removeHeader("User-Agent")//移除旧的
                                                //.removeHeader("Content-Type")//移除旧的
                                                .header("Content-Type", "application/json; charset=UTF-8")//@Headers({"Content-Type: application/json", "Accept: application/json"})//需要添加头
                                                .header("User-Agent", Parameterkey.USER_AGENT_PREFIX + WebSettings.getDefaultUserAgent(Utils.getApp()))//添加真正的头部
                                                .header("Devicecode", MMKV.defaultMMKV().decodeString(ConstantSign.P_UUID_UNIQUEDEVICEID_ANDROIDID, DeviceUtils.getUniqueDeviceId()))//Devicecode: 268c7c773de7b3cc1af50370275699324
                                                //.addHeader("Usertoken", MMKV.defaultMMKV().decodeString(ConstantApi.P_TOKEN))//Usertoken: f731344a03d4a273fc8437628490634e
                                                .build();

                                    } else if (TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_UUID_UNIQUEDEVICEID_ANDROIDID, DeviceUtils.getUniqueDeviceId()))
                                            && !TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN))) {

                                        request = chain.request()
                                                .newBuilder()
                                                //.removeHeader("User-Agent")//移除旧的
                                                //.removeHeader("Content-Type")//移除旧的
                                                .header("Content-Type", "application/json; charset=UTF-8")//@Headers({"Content-Type: application/json", "Accept: application/json"})//需要添加头
                                                .header("User-Agent", Parameterkey.USER_AGENT_PREFIX + WebSettings.getDefaultUserAgent(Utils.getApp()))//添加真正的头部
                                                //.addHeader("Devicecode", MMKV.defaultMMKV().decodeString(ConstantApi.P_UUID_UNIQUEDEVICEID_ANDROIDID))//Devicecode: 268c7c773de7b3cc1af50370275699324
                                                .header("Usertoken", MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN))//Usertoken: f731344a03d4a273fc8437628490634e
                                                .build();

                                    } else if (TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_UUID_UNIQUEDEVICEID_ANDROIDID, DeviceUtils.getUniqueDeviceId()))
                                            && TextUtils.isEmpty(MMKV.defaultMMKV().decodeString(ConstantSign.P_TOKEN))) {

                                        request = chain.request()
                                                .newBuilder()
                                                //.removeHeader("User-Agent")//移除旧的
                                                //.removeHeader("Content-Type")//移除旧的
                                                .header("Content-Type", "application/json; charset=UTF-8")//@Headers({"Content-Type: application/json", "Accept: application/json"})//需要添加头
                                                .header("User-Agent", Parameterkey.USER_AGENT_PREFIX + WebSettings.getDefaultUserAgent(Utils.getApp()))//添加真正的头部
                                                //.addHeader("Devicecode", MMKV.defaultMMKV().decodeString(ConstantApi.P_UUID_UNIQUEDEVICEID_ANDROIDID))//Devicecode: 268c7c773de7b3cc1af50370275699324
                                                //.addHeader("Usertoken", MMKV.defaultMMKV().decodeString(ConstantApi.P_TOKEN))//Usertoken: f731344a03d4a273fc8437628490634e
                                                .build();

                                    }

                                    return chain.proceed(request);
                                }
                            })
                            //.addInterceptor(loggingInterceptor)
                            .connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                            .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                            .writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                            .build();
                }
            }
        }

        return okHttpClient;
    }

    public Retrofit initRetrofitRxJava() {

//        if (retrofit != null) {
//            LogUtils.d(ConstantApi.LOGCAT_NOMAL + "initRetrofitRxJava-retrofit==>" + retrofit + "-->地址是->" + retrofit.baseUrl().url().toString());
//        } else {
//            LogUtils.d(ConstantApi.LOGCAT_NOMAL + "initRetrofitRxJava-retrofit==>null~我设置的");
//        }

        if (retrofit == null) {

            synchronized (NetworkManager.class) {
                if (retrofit == null) {
                    //注释2：设置Retrofit
                    retrofit = new Retrofit.Builder()
                            .client(initClient())//选填
                            //.baseUrl(getReleaseInManger() ? ApiService.OFFICIAL_BASEURL : ApiService.TEST_BASEURL)//动态切换的
                            .baseUrl(public_url_prefix)//动态切换的
                            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())//新增网络请求适配器
                            .addConverterFactory(Retrofit2ConverterFactory.create())//选填(数据转换器，解析)
                            .build();
                }
            }
        }

        return retrofit;
    }

    //特别注释：勿删除，将来使用gson改造版本
//    public static Gson buildGson() {
//        return new GsonBuilder()
//                .setDateFormat("yyyy-MM-dd HH:mm:ss")//因为bug所以转换com.google.gson.JsonSyntaxException#2020-01-03 14:31:13
//                .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
//                .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
//                .create();
//    }

}
